package service

import (
	"errors"
	"fmt"
	"strconv"
	"time"

	"github.com/blog/model"
	"github.com/blog/model/requestModel"
	"github.com/blog/model/responseModel"
	"github.com/bwmarrin/snowflake"
	"gorm.io/gorm"
)

type PostService struct {
	nodeId      *snowflake.Node
	db *gorm.DB
}

func NewPostService(db *gorm.DB ) *PostService {
	n, _ := snowflake.NewNode(1)
	return &PostService{db: db,  nodeId: n}
}



/*
**
列表查询
*/
func (p *PostService) List(userId int, getPostListRequestModel *requestModel.GetPostListRequestModel) (*responseModel.PostsListResponseModel, error) {
	if userId <= 0 {
		return nil, errors.New("请登入后操作")
	}
	if getPostListRequestModel.PageIndex <= 0 {
		getPostListRequestModel.PageIndex = 1
	}
	if getPostListRequestModel.PageSize <= 0 {
		getPostListRequestModel.PageSize = 10
	}
	offset := (getPostListRequestModel.PageIndex - 1) * getPostListRequestModel.PageSize
	list, count, _ := p.SelectList(userId, getPostListRequestModel.State, getPostListRequestModel.Title, offset, getPostListRequestModel.PageSize)
	return &responseModel.PostsListResponseModel{List: list, TotalCount: count}, nil
}


/*
*
更新
*/
func (p *PostService) UpdatePosts(userId int, vo *requestModel.PostsUpdateModel) (bool, error) {
	if userId <= 0 {
		return false, errors.New("请登入后操作")
	}
	fmt.Println(vo)
	id, err := strconv.ParseInt(vo.Id, 10, 64)
	if id <= 0 {
		return false, errors.New("请选择更新文章")
	}
	hasPermission := p.IsAuthorOrmTo(id, userId)
	if !hasPermission {
		return false, errors.New("您无更新权限")
	}
	b, err := p.UpdateById(id, vo.Title, vo.Content, vo.State)
	return b, err
}


/*
*
新增
*/
func (p *PostService) NewPosts(userId int, postsUpdateModel *requestModel.PostsUpdateModel) (int64, error) {
	if userId <= 0 {
		return -1, errors.New("请登入后操作")
	}

	//雪花id
	var id = p.nodeId.Generate().Int64()
	pId, err := p.SaveNew(id, userId, postsUpdateModel.Title, postsUpdateModel.Content)
	return pId, err
}



/*
*
详细信息
*/
func (p *PostService) DetailInfo(id int64) (*model.Post, error) {
	if id <= 0 {
		return nil, errors.New("请选择对应文章")
	}
	return p.SelectById(id)
}



/*
*
删除
*/
func (p *PostService) RemoveById(userId int, postId int64) (bool, error) {
	if userId <= 0 {
		return false, errors.New("请登入后操作")
	}
	if postId <= 0 {
		return false, errors.New("请选择删除文章")
	}
	hasPermission := p.IsAuthorOrmTo(postId, userId)
	if !hasPermission {
		return false, errors.New("您无删除权限")
	}
	return p.RemoveOrmById(postId)
}






//---------- 下面是orm 数据库操作



/*
*
查询列表
*/
func (p *PostService) SelectList(userId int, state int, title string, pageOffset int, pageSize int) (*[]responseModel.PostsResponseModel, int64, error) {
	table := p.db.Debug().Model(&model.Post{})
	table.Select("id,title,SUBSTRING(content,1,100) as content,create_time,state")
	table.Where("user_id = ?", userId)
	if state >= 0 {
		table.Where("state=?", state)
	}
	if len(title) > 0 {
		table.Where("title LIKE ?", "%"+title+"%")
	}
	var totalNum int64
	table.Count(&totalNum)
	table.Limit(pageSize).Offset(pageOffset)
	var list []responseModel.PostsResponseModel
	table.Order("create_time desc").Find(&list)
	table.Find(&list)
	return &list, totalNum, nil
}

func (p *PostService) SelectById(postId int64) (*model.Post, error) {
	var result model.Post
	r := p.db.Where("id=?", postId).First(&result)
	if r.Error != nil {
		return nil, r.Error
	}
	if &result == nil {
		return nil, errors.New("post not found")
	}
	return &result, nil
}

func (p *PostService) IsAuthorOrmTo(id int64, userId int) bool {
	var count int64 = 0
	p.db.Model(&model.Post{}).Where("id=? and user_id=?", id, userId).Count(&count)
	return count > 0
}


// 创建
func (p *PostService) SaveNew(id int64, userId int, title string, content string) (int64, error) {
	var t = time.Now()
	var tempBean = model.Post{Id: id, UserId: userId, Title: title, Content: &content, State: 1, RateNumber: 0, CreateTime: &t}
	r := p.db.Create(&tempBean)
	if r.Error != nil {
		return -1, r.Error
	}
	return id, nil
}

// 更新
func (p *PostService) UpdateById(id int64, title string, content string, state int) (bool, error) {
	var t = time.Now()
	r := p.db.Debug().Model(&model.Post{}).Where("id=?", id).Updates(map[string]interface{}{
		"title":       title,
		"content":     content,
		"state":       state,
		"update_time": t,
	})
	if r.Error != nil {
		return false, r.Error
	}
	return true, nil
}

// 删除
func (p *PostService) RemoveOrmById(postId int64) (bool, error) {
	r := p.db.Where("id=?", postId).Delete(&model.Post{})
	if r.Error != nil {
		return false, r.Error
	}
	return true, nil
}


